package com.hq.tele.hqtelespeechphone;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.common.widget.GroupingListAdapter;
import com.iflytek.cloud.speech.DataUploader;
import com.iflytek.cloud.speech.RecognizerResult;
import com.iflytek.cloud.speech.SpeechConstant;
import com.iflytek.cloud.speech.SpeechError;
import com.iflytek.cloud.speech.SpeechListener;
import com.iflytek.cloud.speech.SpeechUser;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.iflytek.cloud.util.ContactManager;
import com.iflytek.cloud.util.ContactManager.ContactListener;

public class MainActivity extends Activity implements OnGestureListener,
		OnClickListener {

	private GestureDetector gestureDetector;
	final int FLIP_DISTANCE = 100;
	private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
	private View reView;
	private View phoneView;
	private ListView listView;
	private ImageView imageView;
	private GrouplistAdapter grouplistAdapter;
	private boolean isFirstLaunch = false;
	// 识别窗口
	private RecognizerDialog iatDialog;
	// 缓存，保存当前的引擎参数到下一次启动应用程序使用.
	// Tip
	private Toast mToast;
	private SharedPreferences mSharedPreferences;
	// 上传
	private DataUploader dataUploader;
	Handler mHideHandler = new Handler();
	Runnable mHideRunnable = new Runnable() {
		@Override
		public void run() {
			reView.animate().translationX(-150).setDuration(300);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		isFirstLaunch = true;

//		setTitle(R.string.title);
//		((TextView) findViewById(android.R.id.title))
//				.setGravity(Gravity.CENTER);
		setContentView(R.layout.activity_main);
		gestureDetector = new GestureDetector(this, this);

		reView = findViewById(R.id.left_relayout);
		phoneView = findViewById(R.id.left_phone_btn);
		phoneView.setOnClickListener(this);
		imageView = (ImageView) findViewById(R.id.hide_img);
		imageView.setOnClickListener(this);

		listView = (ListView) findViewById(R.id.contacts_list);
		grouplistAdapter = new GrouplistAdapter(this);
		listView.setAdapter(grouplistAdapter);
		listView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				return gestureDetector.onTouchEvent(arg1);
			}
		});

		reView.animate().translationX(-150).setDuration(0);

		// 初始化缓存对象.
		mSharedPreferences = getSharedPreferences(getPackageName(),
				MODE_PRIVATE);
		// 用户登录
		SpeechUser.getUser().login(MainActivity.this, null, null,
				"appid=" + getString(R.string.app_id), listener);

		mToast = Toast.makeText(this, "", Toast.LENGTH_LONG);

		// 创建数据上传实例
		dataUploader = new DataUploader(this);

		if (mSharedPreferences.getBoolean(
				getResources().getString(R.string.if_first_launcher_app), true)) {

			Toast.makeText(this, getString(R.string.text_upload_contacts),
					Toast.LENGTH_SHORT).show();
			ContactManager mgr = ContactManager.createManager(this,
					mContactListener);
			mgr.asyncQueryAllContactsName();
			Editor editor = mSharedPreferences.edit();
			editor.putBoolean(
					getResources().getString(R.string.if_first_launcher_app),
					false);
			editor.commit();
		}

	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	public void onResume() {
		super.onResume();
		AsyncQueryHandler asyncQueryHandler = new AsyncQueryHandler(
				this.getContentResolver()) {
			@Override
			protected void onQueryComplete(int token, Object cookie,
					Cursor cursor) {
				super.onQueryComplete(token, cookie, cursor);
				grouplistAdapter.changeCursor(cursor);
			}
		};
		asyncQueryHandler.startQuery(0x123, null, Phone.CONTENT_URI,
				new String[] { Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER,
						Phone.CONTACT_ID }, Phone.TYPE + "=?",
				new String[] { Phone.TYPE_MOBILE + "" }, null);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return gestureDetector.onTouchEvent(event);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e1.getX() - e2.getX() > FLIP_DISTANCE) {
			// Toast.makeText(this, "1", Toast.LENGTH_SHORT).show();
			reView.animate().translationX(-150).setDuration(300);
		} else if (e2.getX() - e1.getX() > FLIP_DISTANCE) {// 左——右
			// Toast.makeText(this, "2", Toast.LENGTH_SHORT).show();
			reView.animate().translationX(0).setDuration(300);
			delayedHide(AUTO_HIDE_DELAY_MILLIS);
		}
		return false;
	}

	private void delayedHide(int delayMillis) {
		mHideHandler.removeCallbacks(mHideRunnable);
		mHideHandler.postDelayed(mHideRunnable, delayMillis);
	}

	@Override
	public void onLongPress(MotionEvent e) {

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {

		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	private class GrouplistAdapter extends GroupingListAdapter {

		public GrouplistAdapter(Context context) {
			super(context);
		}

		@Override
		public Object getItem(int position) {
			return super.getItem(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return super.getView(position, convertView, parent);
		}

		@Override
		protected void addGroups(Cursor arg0) {
		}

		@Override
		protected void bindChildView(View arg0, Context arg1, Cursor arg2) {
		}

		private void editview(View arg0, Cursor arg2) {
			int name = arg2.getColumnIndex(Phone.DISPLAY_NAME);
			int num = arg2.getColumnIndex(Phone.NUMBER);
			String cname = arg2.getString(name);
			String cnum = arg2.getString(num);
			TextView textView = (TextView) arg0.findViewById(R.id.phone_name);
			TextView textView1 = (TextView) arg0
					.findViewById(R.id.phone_number);
			textView.setText(cname);
			textView1.setText(cnum);
		}

		@Override
		protected void bindGroupView(View arg0, Context arg1, Cursor arg2,
				int arg3, boolean arg4) {
		}

		@Override
		protected void bindStandAloneView(View arg0, Context arg1, Cursor arg2) {
			editview(arg0, arg2);
		}

		@Override
		protected View newChildView(Context arg0, ViewGroup arg1) {
			return null;
		}

		@Override
		protected View newGroupView(Context arg0, ViewGroup arg1) {
			return null;
		}

		@Override
		protected View newStandAloneView(Context arg0, ViewGroup arg1) {
			View view = getLayoutInflater().inflate(R.layout.grouplist_item,
					null);
			return view;
		}

	}

	/**
	 * 用户登录回调监听器.
	 */
	private SpeechListener listener = new SpeechListener() {

		@Override
		public void onData(byte[] arg0) {
		}

		@Override
		public void onCompleted(SpeechError error) {
			if (error != null) {
				Toast.makeText(MainActivity.this,
						getString(R.string.text_login_fail), Toast.LENGTH_SHORT)
						.show();

			} else {
				Toast.makeText(MainActivity.this,
						getString(R.string.text_login_success),
						Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		public void onEvent(int arg0, Bundle arg1) {
		}
	};

	/**
	 * 显示听写对话框.
	 * 
	 * @param
	 */
	public void showIatDialog() {
		if (null == iatDialog) {
			// 初始化听写Dialog
			iatDialog = new RecognizerDialog(this);
		}

		// 获取引擎参数
		String engine = mSharedPreferences.getString(
				getString(R.string.preference_key_iat_engine),
				getString(R.string.preference_default_iat_engine));

		// 清空Grammar_ID，防止识别后进行听写时Grammar_ID的干扰
		iatDialog.setParameter(SpeechConstant.CLOUD_GRAMMAR, null);
		// 设置听写Dialog的引擎
		iatDialog.setParameter(SpeechConstant.DOMAIN, engine);
		// 设置采样率参数，支持8K和16K
		String rate = mSharedPreferences.getString(
				getString(R.string.preference_key_iat_rate),
				getString(R.string.preference_default_iat_rate));
		if (rate.equals("rate8k")) {
			iatDialog.setParameter(SpeechConstant.SAMPLE_RATE, "8000");
		} else {
			iatDialog.setParameter(SpeechConstant.SAMPLE_RATE, "16000");
		}

		// 当DOMAIN设置为POI搜索时,获取area参数
		if ("poi".equals(engine)) {
			String province = mSharedPreferences.getString(
					getString(R.string.preference_key_poi_province),
					getString(R.string.preference_default_poi_province));
			String city = mSharedPreferences.getString(
					getString(R.string.preference_key_poi_city),
					getString(R.string.preference_default_poi_city));

			iatDialog.setParameter(SpeechConstant.SEARCH_AREA, province + city);
		}

		// 清空结果显示框.
		// mResultText.setText(null);
		// 显示听写对话框
		iatDialog.setListener(recognizerDialogListener);
		iatDialog.show();
		showTip(getString(R.string.text_iat_begin));
	}

	private void showTip(String str) {
		if (!TextUtils.isEmpty(str)) {
			mToast.setText(str);
			mToast.show();
		}
	}

	/**
	 * 识别回调监听器
	 */
	RecognizerDialogListener recognizerDialogListener = new RecognizerDialogListener() {
		@Override
		public void onResult(RecognizerResult results, boolean isLast) {
			String text = JsonParser.parseIatResult(results.getResultString());
			// mResultText.append(text);
			// mResultText.setSelection(mResultText.length());
			showTip(text);
		}

		/**
		 * 识别回调错误.
		 */
		public void onError(SpeechError error) {

		}

	};

	/**
	 * 上传联系人 回调监听器.
	 */
	SpeechListener uploadListener = new SpeechListener() {
		/**
		 * 上传结束.
		 */
		public void onCompleted(SpeechError error) {
			if (error != null) {
				showTip(error.toString());
			} else {
				showTip(getString(R.string.text_upload_success));
			}
		}

		@Override
		public void onData(byte[] data) {
		}

		@Override
		public void onEvent(int paramInt, Bundle paramBundle) {
		}
	};
	protected ContactListener mContactListener = new ContactListener() {

		@Override
		public void onContactQueryFinish(String contactInfos, boolean changeFlag) {
			// 注：实际应用中除第一次上传之外，之后应该通过changeFlag判断是否需要上传，否则会造成不必要的流量.
			if (isFirstLaunch) {
				try {
					// 联系人信息需转成utf-8格式的二进制数组
					byte[] datas = ContactManager.getManager()
							.queryAllContactsName().getBytes("utf-8");
					dataUploader.setParameter(SpeechConstant.SUBJECT, "uup");
					dataUploader.setParameter(SpeechConstant.DATA_TYPE,
							"contact");
					dataUploader.uploadData(uploadListener, "contacts", datas);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}

	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.left_phone_btn:
			showIatDialog();
			break;
		case R.id.hide_img:
			reView.animate().translationX(0).setDuration(300);
			delayedHide(AUTO_HIDE_DELAY_MILLIS);
			break;
		default:
			break;
		}
	}
}
